// pages/apply/apply.js
//获取应用实例
const app = getApp()

function scodeItem() {
  var array = [];
  for (var i = -20; i <= 20; i++) {
    if (i <= 0) {
      array.push(i);
    } else {
      array.push("+" + i);
    }
  }
  return array;
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //服务器图片的路径片段
    imgUrl:app.globalData.iconImgUrl,
    backImg: app.globalData.iconImgUrl+"arrow-left.svg",
    pickerNameVisible: false,
    selectedItem: [],
    items: [],
    scodeItemVisible: true,
    current: 'tab1',
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    backIcon: true,
    title: "申请",
    upImgVisible: true,
    formeImg: [],
    hdTabObj: [
      {
        name: "为自己申请",
        active: "active"
      },
      {
        name: "为他人申请",
        active: ""
      }
    ],
    scodeItem: [],
    scodeCount: [],
    array: [
      "固定加扣分项选择",
      "其它加分项选择",
      "加班申请"
    ],
    pickIndex: 0,
    addScode: scodeItem(),
    addScodeIndex: 0,
    addScodeVal: '+10',
    nameArr: [
      "选择人员",
      "张三",
      "李四",
      "马化腾",
      "腾格尔"
    ],
    nameIndex: 0,
    modalVisible: false,
    otherVIsible: false,
    value: [0, 0],
    //表单提交数据开始
    type: 'self',
    subType: 'integral',
    time: '12:01',
    time1: '12:01',
    introduce: '',
    //表单提交数据结束
    otherVal: '',
    integralType: 1
  },
  showModal() {
    this.setData({
      modalVisible: true
    })
  },
  hideModal() {
    this.setData({
      modalVisible: false
    })
    wx.navigateBack()
  },
  changeOtherVal(e) {
    // console.log(e.detail.value)
    this.setData({
      otherVal: e.detail.value
    })
  },
  toApply() {
    var that = this,
      markType = this.data.array[this.data.pickIndex],
      markName = this.data.scodeItem[this.data.value[0]],
      additional = ''
    switch (markType) {
      case '固定加扣分项选择':
        markType = 'regular';
        markName = that.data.scodeItem[that.data.value[0]]
        additional = {
          mark: this.data.scodeCount[this.data.value[1]],
        }
        break;
      case '其它加分项选择':
        markType = 'other';
        markName = this.data.otherVal
        additional = {
          mark: this.data.addScodeVal,
        }
        break;
      case '加班申请':
        markType = 'overTime';
        var date = new Date(),
          year = date.getFullYear() + '.',
          month = date.getMonth() + '.',
          day = date.getDate() + ' '
        additional = {
          beginTime: year + month + day + that.data.time + ":00",
          endTime: year + month + day + that.data.time1 + ":00"
        }
        break;
      default:
        break;
    }

    if (this.data.type === "other") {
      var length = that.data.selectedItem.length,
        nameArr = that.data.selectedItem;
      additional.proposer = []
      additional.proposerCode = []
      for (var i = 0; i < length; i++) {
        additional.proposer.push(nameArr[i].value)
        additional.proposerCode.push(nameArr[i].code)
      }
      // additional.proposer = that.selectedItem
    }
    var data = {
      type: this.data.type,
      subType: this.data.subType,
      Introduce: this.data.Introduce,
      markType: markType,
      markName: markName,
      // mark
      ...additional,
      userCode: wx.getStorageSync('userCode'),
      imgArr: that.data.formeImg
    }
    console.log(data)

    wx.request({
      url: app.globalData.baseUrl + 'application/submit.do',
      data: data,
      method: 'post',
      success(res) {
        console.log(res)
        if (res) {
          that.showModal()
        }
      }
    })
  },
  IntroduceInput(e) {
    console.log(e.detail.value)
    this.setData({
      Introduce: e.detail.value
    })
  },
  handleChange({ detail }) {
    // console.log(detail)
    var subType = 'integral',
      integralType = 1;
    if (detail.key === 'tab1') {
      subType = 'integral'
      integralType = 1
    } else if (detail.key === 'tab2') {
      subType = 'honor'
      integralType = 2
    } else if (detail.key === 'tab3') {
      subType = 'dreamPoint'
      integralType = 3
    }
    this.setData({
      current: detail.key,
      subType: subType,
      integralType: integralType
    });
    this.getPluses()
  },
  TimeChange(e) {
    this.setData({
      time: e.detail.value
    })
  },
  deleteName(e) {
    // console.log(e.target)
    var index = e.target.dataset.index;
    var data = this.data.selectedItem;
    var pickData = this.data.items;
    pickData[index].checked = false;

    // delete data[index];
    data.splice(index, 1)
    console.log(data)
    this.setData({
      selectedItem: data,
      items: pickData
    })
  },
  TimeChange1(e) {
    this.setData({
      time1: e.detail.value
    })
  },
  // bindPickerChange(e) {
  //   console.log('picker发送选择改变，携带值为', e.detail.value)
  //   this.setData({
  //     index: e.detail.value
  //   })
  // },
  bindChange(e) {
    const val = e.detail.value
    const oval = this.data.value
    console.log(val, oval)
    if (val[0] === oval[0]) {
      this.setData({
        value: [val[1], val[1]]
      })
    } else {
      this.setData({
        value: [val[0], val[0]]
      })
    }

  },
  bindPickerChange(e) {
    const val = e.detail.value
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    if (val == 0) {
      this.setData({
        pickIndex: val,
        scodeItemVisible: true,
        otherVIsible: false
      })
    } else if (val == 1) {
      this.setData({
        pickIndex: val,
        scodeItemVisible: false,
        otherVIsible: true
      })
    } else {
      console.log(val)
      this.setData({
        pickIndex: val,
        scodeItemVisible: false,
        otherVIsible: false
      })
    }
  },
  scodeChange(e) {
    const val = e.detail.value;
    this.setData({
      addScodeVal: this.data.addScode[val]
    })
  },
  nameChange() {
    const that = this;
    // console.log(that.data.selectedItem, this.data.items)
    that.setData({
      pickerNameVisible: true
    })

    for (var i = 0; i < that.data.items.length; i++) {
      var item = 'items[' + i + '].checked'
      that.setData({
        [item]: false
      })
      for (var j = 0; j < that.data.selectedItem.length; j++) {

        if (that.data.items[i].name == that.data.selectedItem[j].name) {
          that.setData({
            [item]: true
          })
        }
      }
    }
  },
  hidePickerName() {
    this.setData({
      pickerNameVisible: false
    })
  },
  checkboxChange(e) {
    // console.log('checkbox发生change事件，携带value值为：', e.detail.value)
    var selectedArr = [], indexArr = [], that = this;
    this.data.items.forEach((P_item, index) => {
      var array = e.detail.value.forEach(item => {
        // console.log(P_item.name, item, P_item.name == item)

        if (P_item.name == item) {
          selectedArr.push(P_item);
        }
      })
    })
    // console.log(selectedArr)
    that.setData({
      selectedItem: selectedArr,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },
  takePhoto() {
    var that = this;

    wx.chooseImage({
      // count: 3, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        // success
        var tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: app.globalData.baseUrl + 'application/fileUpload.do', //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name: "file",
          header: {
            "Content-Type": "multipart/form-data"
          },
          success: function (res) {
            var data = res.data
            var item1 = that.data.formeImg[0],
              item2 = that.data.formeImg[1],
              item3 = that.data.formeImg[2],
              imgArr = []
            // console.log(res, item2)
            if (item1 == null) {
              imgArr.push(app.globalData.serverUrl + res.data.split('"')[1])
              that.setData({
                formeImg: imgArr
              })
            }
            // console.log(item2, item2 == null)
            if (item1 != null && item2 == null) {
              that.setData({
                ['formeImg[1]']: app.globalData.serverUrl + res.data.split('"')[1]
              })
            }
            if (item1 != null && item2 != null && item3 == null) {
              that.setData({
                ['formeImg[2]']: app.globalData.serverUrl + res.data.split('"')[1],
                upImgVisible: false
              })
            }

            //do something
          },
          error(err) {
            console.log(err)
          }
        })
      },
      fail: function (errow) {
        // fail
      },
      complete: function () {
        // complete
      }
    })
  },
  p_navTap(param) {
    var index = param.detail.target.dataset.index;
    var item1 = "hdTabObj[" + index + "].active", item2;
    var type;
    if (index === 0) {
      item2 = "hdTabObj[1].active";
      type = "self";
    } else {
      item2 = "hdTabObj[0].active";
      type = "other";
    }

    this.setData({
      [item1]: "active",
      [item2]: '',
      type: type
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var roleId = wx.getStorageSync("userInfo").roleId
    // console.log(roleId)
    this.setData({
      roleId: roleId
    })
    if (roleId === '25') {
      this.setData({
        hdTabObj: [
          {
            name: "为自己申请",
            active: "active"
          }
        ]
      })
    }
    this.getPluses()
    this.getEmployee()
  },
  // 获取加分项列表
  getPluses() {
    const data = {
      "projectType": 3,
      "integralType": this.data.integralType
    }
    const that = this
    // console.log(data, this.data.current)
    wx.request({
      url: app.globalData.baseUrl + 'points/getPointsList.do',
      method: 'post',
      data: data,
      success(res) {
        console.log(res)
        const data = res.data.pointsList;
        var scodeItem = [], scodeCount = []

        data.forEach(item => {
          scodeItem.push(item.projectDesc)
          scodeCount.push(item.score)
        })
        that.setData({
          scodeItem: scodeItem,
          scodeCount: scodeCount
        })

      }
    })
  },
  // 获取选择人员名单
  getEmployee() {
    // console.log(app.globalData.userCode)
    const userCode = wx.getStorageSync("userCode"),
      that = this
    wx.request({
      url: app.globalData.baseUrl + 'employee/getUser.do',
      data: {
        userCode: userCode
      },
      method: 'post',
      success(res) {
        console.log('res', res)
        const nameArr = []
        res.data.userList.forEach(item => {
          nameArr.push({
            value: item.userName,
            name: item.userName,
            code: item.userCode,
            status: 1
          })
        })
        that.setData({
          items: nameArr
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})